package com.nbot.server.config.ds;

import com.alibaba.druid.pool.DruidDataSource;
import com.nbot.server.properties.NbotProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 外部mysql数据库配置
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = FourthDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "fourthSqlSessionFactory")
public class FourthDataSourceConfig {

    @Autowired
    NbotProperties nbotProperties;

    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.nbot.server.mapper.fourth";
    static final String MAPPER_LOCATION = "classpath:mapper/fourth/*.xml";

    @Value("${fourth.datasource.url}")
    private String url;

    @Value("${fourth.datasource.username}")
    private String user;

    @Value("${fourth.datasource.password}")
    private String password;

    @Value("${fourth.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "fourthDataSource")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setMaxActive(50);
        return dataSource;
    }

    @Bean(name = "fourthTransactionManager")
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "fourthSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("fourthDataSource") DataSource thirdDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(thirdDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(FourthDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}